﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using Microsoft.Win32;
using eRechnung.Properties;

namespace eRechnung
{
    public class ZustellSetting
    {
        public enum Zustelldienst
        {
            easyVersand = 0,
            Notepad

        }

        private readonly Zustelldienst _zustelldienst;
        public Zustelldienst Dienst
        {
            get
            {
                return _zustelldienst;
            }
        }

        public string ProgramPath { get; set; }
        public string Parm { get; set; }
        private readonly Image _image;
        public readonly string RegName;
        public readonly string[] RegKeys;
        public bool SignAlways;

        public Image Image
        {
            get
            {
                //var asm = Assembly.GetExecutingAssembly();
                //var bmImage = new Bitmap(asm.GetManifestResourceStream(_image));
                //var resMngr = new ResourceManager("eRechnung.Images",GetType().Assembly);
                //var bmImage = (Bitmap) resMngr.GetObject(_image);
                //return bmImage;
                return _image;
            } 
        }

        public ZustellSetting()
        {
            SignAlways = false;
        }
        public ZustellSetting(Zustelldienst pName, string pPath, string pParm, Image pImage, string pRegname, string[] pregKeys)
        {
            _zustelldienst = pName;
            ProgramPath = pPath;
            Parm = pParm;
            _image = pImage;
            RegName = pRegname;
            RegKeys = pregKeys;
        }

        public string GetProgramPath()
        {
            if (File.Exists(ProgramPath))
            {
                return ProgramPath;
            }
            string Progname = Path.GetFileName(ProgramPath);
            string retval = "";
            foreach (string regKey in RegKeys)
            {
                object regtal = Registry.GetValue(regKey, RegName, "Not Found");
                if (regtal!=null)
                {
                    string regVal = regtal.ToString();
                    if (regVal!="Not Found")
                    {
                        retval = Path.Combine(regVal, Progname);
                        if (File.Exists(retval))
                        {
                            return retval;
                        }
                    }
                }

            }
            return retval;
            // return RegKeys.Select(regKey => Registry.GetValue(regKey, RegName, "Not Found").ToString()).Where(regVal => regVal != "Not Found").Select(regVal => Path.Combine(regVal, Progname)).Where(File.Exists).FirstOrDefault();
        }
    }

    public class ZustellSettings : Dictionary<ZustellSetting.Zustelldienst, ZustellSetting>
    {
        /// <summary>
        /// Erzeugt einen XML String aus der Zustellsettingsliste
        /// </summary>
        /// <returns></returns>
        public string ToXml()
        {
            //var serial = new XmlSerializer(typeof(ZustellSettings));
            var serial = new DataContractSerializer(typeof (ZustellSettings));
            using (var wrt = new StringWriter())
            {
                using (var writer = new XmlTextWriter(wrt))
                {
                    serial.WriteObject(writer,this);
                    writer.Flush();
                    return wrt.ToString();
                }
            }

        }

        /// <summary>
        /// Erzeugt eine Liste aus dem XML String
        /// </summary>
        /// <param name="zsString"></param>
        /// <returns></returns>
        public static ZustellSettings FromXml(string zsString)
        {
            var deser = new XmlSerializer(typeof(ZustellSettings));
            using (var rdr = new StringReader(zsString))
            {
                return (ZustellSettings)deser.Deserialize(rdr);
            }
        }

        public static ZustellSettings LoadSettings()
        {
            //string xmlstr = Settings.Default.setZustellung;
            //if (xmlstr == null)
            //{
            //    return new ZustellSettings();
            //}
            //return FromXml(xmlstr);
            ZustellSettings zs = Settings.Default.setZustellung;
            if (zs==null)
            {
                zs = new ZustellSettings();
            }
            return zs;
        }

        public void SaveSettings()
        {
            // string xmlstr = ToXml();
            Settings.Default.setZustellung = this;
            Settings.Default.Save();
        }

        public ZustellSetting GetItem(string name)
        {
            ZustellSetting.Zustelldienst zsDienst;
            if (!Enum.TryParse(name, out zsDienst))
            {
                return null;
            }

            if (!Enum.IsDefined(typeof(ZustellSetting.Zustelldienst), zsDienst))
            {
                return null;
            }

            return this[zsDienst];

        }

        public static ZustellSettings LoadDefaults()
        {
            return new ZustellSettings
                              {
#if DEBUG
                                  {
                                      ZustellSetting.Zustelldienst.Notepad,
                                      new ZustellSetting(ZustellSetting.Zustelldienst.Notepad,
                                                         @"C:\Windows\System32\Notepad.exe",
                                                         "[eRechnung]",
                                                         Images.Notepad_32x32,
                                                         "",
                                                         new string[]{""})
                                      },
#endif
                                  {
                                      ZustellSetting.Zustelldienst.easyVersand,
                                      new ZustellSetting(ZustellSetting.Zustelldienst.easyVersand,
                                                         @"C:\Program Files\exthex GmbH\exDP Client\exDPClient.exe",
                                                         "-o deliver [eRechnung]",
                                                         Images.Easyversand_100x70,
                                                         "location",
                                                         new string[]{@"HKEY_CURRENT_USER\SOFTWARE\exthex GmbH\exDP",
                                                         @"HKEY_LOCAL_MACHINE\SOFTWARE\exthex GmbH\exDP"})
                                      }
                              };
        }
    }

}
